/**
 * n8n工具到MCP协议的适配器
 *
 * 将现有的n8n工具包转换为符合MCP协议的格式
 */

import type { ToolFunction, ToolMeta, DslSchema, FieldSchema, Tool } from '../core/tool-schema.js';

/**
 * 将工具元数据转换为MCP工具格式
 */
export function toolMetaToMcpTool(meta: ToolMeta, handler: ToolFunction): Tool {
  // 转换参数定义
  const schema: DslSchema | undefined =
    meta.parameters && Object.keys(meta.parameters).length > 0
      ? {
          properties: convertParameters(meta.parameters),
          required: getRequiredFields(meta.parameters),
          additionalProperties: false,
        }
      : undefined;

  return {
    name: meta.name,
    description: meta.description,
    schema,
    execute: async (params: any) => {
      try {
        const result = await handler(params);
        return result;
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error),
        };
      }
    },
  };
}

/**
 * 转换参数定义
 */
function convertParameters(parameters: Record<string, any>): Record<string, FieldSchema> {
  const converted: Record<string, FieldSchema> = {};

  for (const [name, field] of Object.entries(parameters)) {
    converted[name] = convertFieldSchema(field);
  }

  return converted;
}

/**
 * 转换单个字段定义
 */
function convertFieldSchema(field: any): FieldSchema {
  const schema: FieldSchema = {
    type: field.type || 'any',
    description: field.description,
  };

  // 处理必填属性
  if (field.required !== undefined) {
    schema.required = field.required;
  }

  // 处理默认值
  if (field.default !== undefined) {
    schema.default = field.default;
  }

  // 处理枚举
  if (field.enum) {
    schema.enum = field.enum;
  }

  // 字符串特有属性
  if (field.type === 'string') {
    if (field.minLength !== undefined) schema.minLength = field.minLength;
    if (field.maxLength !== undefined) schema.maxLength = field.maxLength;
    if (field.pattern) schema.pattern = field.pattern;
  }

  // 数字特有属性
  if (field.type === 'number') {
    if (field.min !== undefined) schema.min = field.min;
    if (field.max !== undefined) schema.max = field.max;
    if (field.minimum !== undefined) schema.minimum = field.minimum;
    if (field.maximum !== undefined) schema.maximum = field.maximum;
  }

  // 数组特有属性
  if (field.type === 'array' && field.items) {
    schema.items = convertFieldSchema(field.items);
  }

  // 对象特有属性
  if (field.type === 'object' && field.properties) {
    schema.properties = convertParameters(field.properties);
  }

  return schema;
}

/**
 * 获取必填字段列表
 */
function getRequiredFields(parameters: Record<string, any>): string[] {
  const required: string[] = [];

  for (const [name, field] of Object.entries(parameters)) {
    if (field.required === true) {
      required.push(name);
    }
  }

  return required;
}

/**
 * 批量转换工具包
 */
export function convertToolPackage(
  tools: Array<{ meta: ToolMeta; handler: ToolFunction }>
): Tool[] {
  return tools.map(({ meta, handler }) => toolMetaToMcpTool(meta, handler));
}
